package com.qf.service.impl;

import com.qf.api.CacheFeign;
import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainService;
import com.qf.util.PushMsgUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

/**
 * @author WzYu
 * @date 2022-6-9 下午 8:16
 */
@Service(value = "limitFiveMinutes")
@Slf4j
public class LimitFiveMinutesServiceImpl implements FilterChainService {

    @Autowired
    private CacheFeign cacheFeign;
    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("[策略模块 - 限流策略] 5分钟内的限流策略开始执行！！！");
        //1获取客户id和目标手机号  组成key
        Integer clientID = standardSubmit.getClientID();
        String destMobile = standardSubmit.getDestMobile();
        //2校验短信内容是否相同   给key添加个前缀  短信内容
        String key = CacheConstants.CACHE_PREFIX_SMS_LIMIT + clientID + ":" + destMobile;
        //3获取发送时间的毫秒值  和他5分钟之前的毫秒值
        long sendTime=new Date().getTime();
        long wufenzhongzhihou = sendTime - 1000 * 60 * 5;
        //4调用缓存模块  查询5分钟之内发送几条短信
        Set<Object> value = cacheFeign.zRangeByScore(key, wufenzhongzhihou, sendTime);
        //5判断发送条数
        if (value !=null&&value.size()>=3){
            log.info("[策略模块 - 限流策略] 5分钟内的限流策略执行失败。。。");
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);

            pushMsgUtil.pushReport(standardSubmit,StrategyConstants.STRATEGY_ERROR_LIMIT);
            return false;
        }
        log.info("[策略模块 - 限流策略] 5分钟内的限流策略执行失败。。。");
        return true;
    }
}
